// miniprogram/pages/NX_newProject/newProject.js
const db = wx.cloud.database();
Page({
    /**
     * 页面的初始数据
     */
    data: {
        position: null, //lat,lng
        teamNum: ['', '', '', ''],
        value: '',
        focus: false,
        inputed: false,
        canAnime: getApp().globalData.platform !== 'ios',
        getInfo: false,
        createTeam: null,
        groupInfo: null,
        movedCreator: false,
        member: [],
        codeId: null,
        confirm: false,
    },
    submitf2f() {
        if (this.data.position) {
            wx.cloud.callFunction({
                name: 'makeGroup',
                data: {
                    userId: getApp().globalData.userInfo.userId,
                    code: this.data.value,
                    position: this.data.position,
                }
            })
                .then(res => {
                    this.setData({
                        getInfo: true,
                        createTeam: res.result.create,
                        groupInfo: res.result.group,
                        member: res.result.member,
                        codeId: res.result.codeId,
                        movedCreator: false
                    })
                    setTimeout(this.getGroupInfo, 500);
                })
        }
    },
    doconfirm() {
        this.data.getInfo = false;
        if (this.data.codeId) {
            //添加项目到个人记录
            const isLeader = this.data.createTeam || this.data.movedCreator;
            wx.cloud.callFunction({
                name: 'confirmJoinGroup',
                data: {
                    userId: getApp().globalData.userInfo.userId,
                    groupId: this.data.groupInfo._id,
                    isLeader
                }
            }).then(() => {
                this.setData({
                    confirm: true
                })
                if (isLeader) {
                    wx.redirectTo({
                        url: '../NX_setProject/setProject?projectId=' + this.data.groupInfo._id + '&create=true',
                    })
                } else {
                    wx.navigateBack()
                }
            }).catch(err => console.log(err))
        }
    },
    getGroupInfo() {
        console.log('getInfo');
        if (this.data.getInfo && this.data.groupInfo && this.data.groupInfo._id) {
            const memberIds = this.data.member.map(usr => usr._id);
            wx.cloud.callFunction({
                name: 'getGroupInfo',
                data: {
                    group: this.data.groupInfo._id,
                    // code: this.data.value,
                    memberIds
                }
            }).then(res => {
                console.log(res);
                if (this.data.getInfo) {
                    setTimeout(this.getGroupInfo, 500);
                    const member = res.result
                    if(!member||!member.length) return;
                    this.setData({
                        movedCreator: !this.data.groupInfo.create && member[0].userId === getApp().globalData.userInfo.userId,
                        member
                    })
                }
            }).catch(err => {
                console.log(err);
                setTimeout(this.getGroupInfo,500);
            })

        }

    },
    exitGroup() {
        wx.cloud.callFunction({
            name: 'delCode',
            data: {
                groupId: this.data.groupInfo._id,
                userId: getApp().globalData.userInfo.userId,
                code: this.data.value
            }
        }).catch(err => console.error(err))
        this.setData({
            value: '',
            teamNum: ['', '', '', ''],
            inputed: false,
            focus: true,
            codeId: null,
            getInfo: false,
            groupInfo: null,
            member: [],
        })

    },

    oninput(e) {
        const res = (e.detail.value).toString();
        this.data.teamNum = ['', '', '', ''];
        for (let i = 0; i < res.length; i++) {
            this.data.teamNum[i] = res[i]
        }
        if (res.length > 3) {
            this.setData({
                focus: false,
                inputed: true,
                teamNum: this.data.teamNum,
                value: res
            })
            this.submitf2f();
        } else {
            this.setData({
                inputed: false,
                teamNum: this.data.teamNum,
                value: res
            })
        }
    },
    doinput() {
        if (this.data.inputed) {
            this.exitGroup()
        } else {
            this.setData({
                focus: true
            })
        }
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {

    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        wx.getLocation({
            success: (res) => {
                const {
                    latitude,
                    longitude
                } = res;
                this.setData({
                    position: {
                        lat: latitude,
                        lng: longitude,
                    },
                    focus: true
                })
            },
            fail(res) {
                // if (res.errCode === 2) {
                    wx.showModal({
                        title: '哦……发生了错误',
                        content: '请尝试开启手机定位',
                        showCancel: false,
                        complete() {
                            wx.navigateBack()
                        }
                    })
                // } else {
                    // console.log(res)
                // }
            }
        })
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {
        if (this.data.getInfo && !this.data.confirm) {
            this.exitGroup()
        }
        this.setData({
            position: null,
        })
    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {
        if (this.data.getInfo && !this.data.confirm) {
            this.exitGroup()
        }
    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },


})